﻿namespace Vben.Core.Module.Sys;

public class SysCoopUserService : BaseMainService<SysCoopUser>, ITransient
{


    public async Task<string> Insert(SysCoopUser main)
    {
        main.id = YitIdHelper.NextId() + "";
        if (!string.IsNullOrEmpty(main.corid))
        {
            var corp = await _corpRepo.GetSingleAsync(t => t.id == main.corid);
            var cate = await _cateRepo.GetSingleAsync(t => t.id == corp.catid);
            main.tier = cate.tier + corp.id + "x" + main.id + "x";
        }
        else
        {
            main.tier = "x" + main.id + "x";
        }
        await InsertAsync(main);
        SysOrg sysOrg = new SysOrg(main.id, main.name, 256);
        await _orgRepo.InsertAsync(sysOrg);
        return main.id;
    }


    public async Task<string> Update(SysCoopUser main)
    {
        if (!string.IsNullOrEmpty(main.corid))
        {
            var corp = await _corpRepo.GetSingleAsync(t => t.id == main.corid);
            var cate = await _cateRepo.GetSingleAsync(t => t.id == corp.catid);
            main.tier = cate.tier + corp.id + "x" + main.id + "x";
        }
        else
        {
            main.tier = "x" + main.id + "x";
        }
        await UpdateAsync(main);
        SysOrg sysOrg = new SysOrg(main.id, main.name, 256);
        await _orgRepo.UpdateAsync(sysOrg);
        return main.id;
    }

    public async Task Delete(string ids)
    {
        await DeleteAsync(ids);
        await repo.Context.Deleteable<SysOrg>().In(ids).ExecuteCommandAsync();
    }

    public async Task ResetPacod(PacodPo po)
    {
        po.pacod = SecureUtils.PasswordEncrypt(po.pacod);
        string sql = "update sys_coop_user set pacod=@pacod where id=@id";
        await repo.Context.Ado.ExecuteCommandAsync(sql, new { id = po.id, pacod = po.pacod });
    }


    private SqlSugarRepository<SysOrg> _orgRepo;

    private SqlSugarRepository<SysCoopCorp> _corpRepo;

    private SqlSugarRepository<SysCoopCate> _cateRepo;
    public SysCoopUserService(SqlSugarRepository<SysCoopUser> repo,
    SqlSugarRepository<SysOrg> orgRepo,
    SqlSugarRepository<SysCoopCorp> corpRepo,
    SqlSugarRepository<SysCoopCate> cateRepo)
    {
        this.repo = repo;
        _orgRepo = orgRepo;
        _corpRepo = corpRepo;
        _cateRepo = cateRepo;
    }
}